import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from common.handleconfig import conf


def sendemail(filename, title):
    # 第一步：连接邮箱的smtp服务器，并登录
    smtp = smtplib.SMTP_SSL(host=conf.get("email", "host"), port=conf.get("email", "port"))
    smtp.login(user=conf.get("email", "user"), password=conf.get("email", "password"))

    # 第二步：构建一封邮件
    msg = MIMEMultipart()  # 创建一封多组件的邮件
    with open(filename, "rb") as f:
        content = f.read()

    text_msg = MIMEText(content, _subtype="html", _charset="utf-8")  # 创建邮件文本内容
    msg.attach(text_msg)  # 将文本内容添加到多组件的邮件中

    report_file = MIMEApplication(content)  # 创建邮件附件
    report_file.add_header("content-disposition", "attachment", filename=filename)
    msg.attach(report_file)  # 将附件添加到多组件的邮件中

    msg["Subject"] = title  # 主题
    msg["From"] = conf.get("email", "from_addr")  # 发件人
    msg["To"] = conf.get("email", "to_addrs")  # 收件人（邮件显示的邮件名）

    # 第三步：发送邮箱
    smtp.send_message(msg, from_addr=conf.get("email", "from_addr"), to_addrs=conf.get("email", "to_addrs"))
